

import request from '../request.js'
export default {
    data() {
        return {
            pc: null, //RTCPeerConnection
        }
    },
   
    methods: {
        webrtcStartVideo(dom,url) {
            let urlObject = this.parse_rtmp_url(this.url||url);
            let schema = window.location.protocol;

            // Close this.pc when user replay.
            if (this.pc) {
                this.pc.close();
            }

            this.pc = new RTCPeerConnection(null);
            this.pc.onaddstream = (event)=>{
                dom.autoplay = true;
                dom.srcObject = event.stream;
            }
            new Promise((resolve, reject) =>{
                this.pc.addTransceiver("audio", {direction: "recvonly"});
                this.pc.addTransceiver("video", {direction: "recvonly"});
                this.pc.createOffer(function(offer){
                    resolve(offer);
                },function(reason){
                    reject(reason);
                });
            }).then((offer) => {
                return this.pc.setLocalDescription(offer).then(function(){ return offer; });
            }).then((offer) => {
                return new Promise(function(resolve, reject) {
                    let port = urlObject.port || 1985;
                    // @see https://github.com/rtcdn/rtcdn-draft
                    let api = urlObject.user_query.play || '/rtc/v1/play/';
                    if (api.lastIndexOf('/') != api.length - 1) {
                        api += '/';
                    }

                    let url = schema + '//' + urlObject.server + ':' + port + api;
                    for (let key in urlObject.user_query) {
                        if (key != 'api' && key != 'play') {
                            url += '&' + key + '=' + urlObject.user_query[key];
                        }
                    }
                    // Replace /rtc/v1/play/&k=v to /rtc/v1/play/?k=v
                    url = url.replace(api + '&', api + '?');

                    // @see https://github.com/rtcdn/rtcdn-draft
                    let data = {
                        api: url, streamurl: urlObject.url, clientip: null, sdp: offer.sdp
                    };
                    console.log("Generated offer: ", data);
                     request({
                        url: url,
                        method: 'post',
                        data
                    }).then(res=>{
                        resolve(res.data.sdp)
                        
                    }).catch(err=>{
                        reject(err)
                    })               
                });
            }).then((answer) => {
                return this.pc.setRemoteDescription(new RTCSessionDescription({type: 'answer', sdp: answer}));
            }).catch((reason) => {
                throw reason;
            });
        },
        parse_rtmp_url(rtmp_url){
            let a = document.createElement("a");
            a.href = rtmp_url.replace("rtmp://", "http://")
                .replace("webrtc://", "http://")
                .replace("rtc://", "http://");

            let vhost = a.hostname;
            let app = a.pathname.substr(1, a.pathname.lastIndexOf("/") - 1);
            let stream = a.pathname.substr(a.pathname.lastIndexOf("/") + 1);

            // parse the vhost in the params of app, that srs supports.
            app = app.replace("...vhost...", "?vhost=");
            if (app.indexOf("?") >= 0) {
                let params = app.substr(app.indexOf("?"));
                app = app.substr(0, app.indexOf("?"));

                if (params.indexOf("vhost=") > 0) {
                    vhost = params.substr(params.indexOf("vhost=") + "vhost=".length);
                    if (vhost.indexOf("&") > 0) {
                        vhost = vhost.substr(0, vhost.indexOf("&"));
                    }
                }
            }

            // when vhost equals to server, and server is ip,
            // the vhost is __defaultVhost__
            if (a.hostname == vhost) {
                let re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
                if (re.test(a.hostname)) {
                    vhost = "__defaultVhost__";
                }
            }
            
            // parse the schema
            let schema = "rtmp";
            if (rtmp_url.indexOf("://") > 0) {
                schema = rtmp_url.substr(0, rtmp_url.indexOf("://"));
            }

            let port = a.port;
            if (!port) {
                if (schema === 'http') {
                    port = 80;
                } else if (schema === 'https') {
                    port = 443;
                } else if (schema === 'rtmp') {
                    port = 1935;
                } else if (schema === 'webrtc' || schema === 'rtc') {
                    port = (window.location.href.indexOf('https://')==0)? 443:1985;
                }
            }

            let ret = {
                url: rtmp_url,
                schema: schema,
                server: a.hostname, port: port,
                vhost: vhost, app: app, stream: stream
            };
            this.__fill_query(a.search, ret);

            return ret;
        },
        __fill_query(query_string, obj) {
            // pure user query object.
            obj.user_query = {};

            if (query_string.length == 0) {
                return;
            }

            // split again for angularjs.
            if (query_string.indexOf("?") >= 0) {
                query_string = query_string.split("?")[1];
            }

            var queries = query_string.split("&");
            for (var i = 0; i < queries.length; i++) {
                var elem = queries[i];

                var query = elem.split("=");
                obj[query[0]] = query[1];
                obj.user_query[query[0]] = query[1];
            }

            // alias domain for vhost.
            if (obj.domain) {
                obj.vhost = obj.domain;
            }
        }

    }
};

